<template>
  <div class="wrap">
    <div class="main">
      <m-header></m-header>
      <div></div>
      <div class="msg-wrap">
        <div class="left" v-if="!videoStatus">
          <div
            class="item"
            v-for="item in conversationList"
            :class="item.receiverId == activeIndex ? 'activeIndex' : ''"
            :key="item.id"
            @click="chooseUser(item)"
          >
            <img class="avatar" :src="item.receiverImg" />
            <div class="text">
              <p class="name">{{ item.receiverName }}</p>
              <p>id:{{ item.receiverId }}</p>
            </div>
          </div>
        </div>
        <div class="video" v-else>
          <video-chat ref="videoChat"></video-chat>
          <!-- <video-chat2></video-chat2> -->
        </div>
        <div class="right">
          <div class="top">{{ currentchatter.receiverName || "  " }}</div>
          <div class="chatList" ref="chatList">
            <div
              v-for="item in messageList"
              :key="item.id"
              :class="
                item.receiver == currentchatter.receiverId
                  ? 'con-left'
                  : 'con-right'
              "
            >
              <!-- receiver:本人 sender:对方 -->
              <div
                class="receiver item"
                v-if="item.receiver == currentchatter.receiverId"
              >
                <p class="content">{{ item.message }}</p>
                <img :src="userInfo.avatar" alt="" />
              </div>
              <div class="sender item" v-else>
                <img :src="currentchatter.receiverImg" alt="" />
                <p class="content">{{ item.message }}</p>
                <!-- 视频邀请 -->
                <Button class="receiveBtn" 
                v-if="item.type == 1" 
                type="success" 
                size="small"
                @click="receiveVideo()">
                  接受
                </Button>
              </div>
            </div>
          </div>
          <div class="interact">
            <span class="iconfont icon-iconweixiao"></span>
            <span class="iconfont icon-xingzhuang" @click="inviteConnect()"></span>
          </div>
          <div class="chatInput">
            <Input
              v-model="message"
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 4 }"
              placeholder="请输入聊天内容"
            />
            <div class="btn">
              <Button @click="sendMsg" type="primary">发送</Button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import mHeader from "@/components/header.vue";
import videoChat from "./children/videoChat.vue";
import videoChat2 from "./children/videoChat2.vue";
import socket from "@/plugins/socketIO";
import { getSession, setLocal, getLocal } from "../../utils/index.js";

export default {
  components: {
    mHeader,
    videoChat,
    videoChat2,
  },
  data() {
    return {
      conversationList: [], // 聊天对象列表
      activeIndex: "", // 当前聊天对象id
      currentchatter: {}, // 当前聊天对象
      messageList: [], // 消息列表
      message: "", // 消息
      videoStatus: false, // 是否视频通话
      userInfo:{},
      socketMap:{},

      // 测试
      listClients: [],
      sender: "",
      receiver: "",
    };
  },
  created() {
    let userInfo = getSession("userInfo");
    this.userInfo = userInfo;
    // 测试
    socket.on("listClients", (data) => {
      this.listClients = data 
    });
    // 获取socketMap
    socket.on('getSocketMap',data => {
      console.log('socketMap',data);
      this.socketMap = data
    })
    let { id } = this.$route.query;
    this.getAllUser(id);
    this.getInstantMsg();
  },
  watch: {
    messageList(newVal, oldVal) {
      this.$nextTick(() => {
        this.$refs.chatList.scrollTop = this.$refs.chatList.scrollHeight;
      });
    },
  },
  methods: {
    // 获取聊天列表
    getAllUser(currentId) {
      this.activeIndex = currentId;
      let { id } = getSession("userInfo");
      this.HttpService.getConversation({ id: id }).then((res) => {
        // console.log(res);
        let data = res.data;
        data.map((item) => {
          if (item.receiverId == currentId) {
            this.currentchatter = item;
          }
        });
        this.conversationList = data;
        // 正常进入message页面(没有传递参数) 默认显示第一个
        if (!currentId) {
          this.currentchatter = data[0];
          let receiverId = this.currentchatter.receiverId;
          this.activeIndex = receiverId;
          this.getPrivateMsg(id, receiverId);
        } else {
          this.getPrivateMsg(id, currentId);
        }
      });
    },
    // 选中聊天对象
    chooseUser(item) {
      if (item == this.currentchatter) return;
      this.messageList = [];
      let { id } = getSession("userInfo");
      this.currentchatter = item;
      this.activeIndex = item.receiverId;
      this.getPrivateMsg(id, item.receiverId);
    },
    // 获取消息
    getPrivateMsg(sender, receiver) {
      this.HttpService.getPrivateMsg({
        sender: sender,
        receiver: receiver,
      }).then((res) => {
        this.messageList = res.data;
      });
    },
    // 发送消息
    sendMsg() {
      let msg = this.message;
      if (msg.replace(/(^s*)|(s*$)/g, "").length == 0 || msg.trim() == "") {
        msg = "";
        this.$Message.warning("消息不可为空哦");
        return;
      }
      let { receiverId } = this.currentchatter;
      let { id } = getSession("userInfo");
      socket.emit("sendPrivateMsg", {
        message: msg,
        receiver: receiverId,
      });
      let map = {
        type: 0,
        message: this.message,
        sender: id,
        receiver: receiverId,
      };
      // 存入数据库
      this.HttpService.sendPrivateMsg(map).then((res) => {
        console.log(res);
      });
      this.messageList.push(map);
      this.message = "";
    },
    // 获取实时信息
    getInstantMsg() {
      socket.removeAllListeners("getPrivateMsg");
      socket.on("getPrivateMsg", (data) => {
        console.log('收到私信:',data);
        this.messageList.push(data);
        this.$refs.chatList.scrollTop = this.$refs.chatList.scrollHeight;
      });
    },
    // 视频邀请
    inviteConnect() {
      let { receiverId } = this.currentchatter;
      let { id } = getSession("userInfo");
      socket.emit("sendPrivateMsg", {
        type:1,
        message: "我发起了视频通话邀请",
        receiver: receiverId,
      });
      let map = {
        type: 1,
        message: "我发起了视频通话邀请",
        sender: id,
        receiver: receiverId,
      };
      // 存入数据库
      this.HttpService.sendPrivateMsg(map).then((res) => {
        console.log(res);
      });
      this.messageList.push(map);
      this.videoStatus = true;
    },
    // 接收邀请
    receiveVideo(){
      this.videoStatus = true;
      setTimeout(() => {
        let curchatterId = this.currentchatter.receiverId;
        let senderId = this.userInfo.id
        let receiver = this.socketMap[curchatterId];
        let sender = this.socketMap[senderId];
        this.$refs.videoChat.event(receiver,sender);
      },1500)
    }
  },
};
</script>

<style lang='less' scoped>
.msg-wrap {
  display: flex;
  width: 980px;
  margin: 0px auto;
  position: relative;
  top: 20px;
  height: 80vh;
  .left {
    width: 29%;
    background-color: #fff;
    margin-right: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
    height: 100%;
    overflow-y: scroll;
    .item {
      padding: 18px 10px;
      display: flex;
      cursor: pointer;
      img {
        width: 50px;
        height: 50px;
        border-radius: 50%;
      }
      .text {
        margin-left: 20px;
        .name {
          font-size: 16px;
        }
      }
    }
    .item:hover {
      background-color: #f1f1f1;
    }
  }
  .video {
    width: 29%;
    background-color: #fff;
    margin-right: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
    height: 100%;
  }
  .right {
    width: 70%;
    background-color: #fff;
    border: 1px solid #ddd;
    border-radius: 5px;
    overflow-y: hidden;
    height: 100%;
    .top {
      text-align: center;
      background-color: #f6f6f6;
      line-height: 50px;
      height: 50px;
    }
    .chatList {
      height: 50%;
      border-top: 1px solid #ddd;
      border-bottom: 1px solid #ddd;
      overflow-y: scroll;
      position: relative;
      .item {
        margin: 15px 10px;
        img {
          width: 40px;
          height: 40px;
          border-radius: 50%;
        }
        p {
          background-color: #ebf8f5;
          padding: 5px 10px;
          color: #666;
          border-radius: 5px;
        }
      }
      .con-left {
        display: flex;
        justify-content: right;
        .receiver {
          display: flex;
          align-items: center;
          p {
            margin-right: 10px;
          }
        }
      }
      .con-right {
        display: flex;
        .sender {
          display: flex;
          align-items: center;
          p {
            margin-left: 10px;
          }
        }
      }
    }
    .interact {
      display: flex;
      align-items: center;
      margin: 5px 0px;
      span {
        font-size: 20px;
        cursor: pointer;
        margin-left: 20px;
      }
    }
    .chatInput {
      flex: 2;
      padding: 0px 10px 0px 10px;
      position: relative;
      height: 150px;
      .btn {
        position: absolute;
        right: 10px;
        bottom: 10px;
      }
    }
  }
}
.activeIndex {
  background-color: #f1f1f1;
}
.receiveBtn{
  margin-left: 10px;
}
</style>
